/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.dataset.session;

import java.sql.*;

import nfse.*;
import nfse.gui.record.FlexRecord;
import nfse.gui.record.FlexRecordField;

/*******************************************************************************
 * Generic network connection (sessoin) data structure.
 * 
 * @author
 * 
 * This code is the property of Los Alamos National Laboratory and the
 * University of California, Copyright 2005
 */
public abstract class Session extends NetFSERecord {

    /***************************************************************************
     * The sensor ID that generated this record
     */
    public int sensor = -1;

    /***************************************************************************
     * The destination address as a dot quad (e.g. 1.2.3.4)
     */
    public String dstAddr = "";

    public long dstIP = -1;

    /***************************************************************************
     * The TCP destination port
     */
    public int dstPort = -1;

    /***************************************************************************
     * The TCP source port
     */
    public int srcPort = -1;

    /***************************************************************************
     * The number of packets sent by the destination host
     */
    public long dstPkts = -1;

    /***************************************************************************
     * The number of packets sent by the source host
     */
    public long srcPkts = -1;

    /***************************************************************************
     * The number of bytes sent by the destination host
     */
    public long dstBytes = -1;

    /***************************************************************************
     * The number of bytes sent by the source host
     */
    public long srcBytes = -1;

    protected java.sql.Timestamp stopTS = null;

    /***************************************************************************
     * The protocol identifier for this session
     */
    public int proto = -1;

    public String createMergeTableSQL(String table, String[] tableNames) {
        StringBuffer temp = new StringBuffer("create table ");
        temp.append(table);
        temp.append("(");
        temp.append("srcip bigint");
        temp.append(",");
        temp.append("dstip bigint");
        temp.append(",");
        temp.append("dstport int");
        temp.append(",");
        temp.append("startts datetime");
        temp.append(",");
        temp.append("record blob");
        temp.append(",");
        temp.append("record_hex blob");
        temp.append(") ENGINE=MERGE UNION (");
        for (int i = 0; i < tableNames.length; i++) {
            if (i > 0)
                temp.append(",");
            temp.append(tableNames[i]);
        }
        temp.append(") INSERT_METHOD=LAST");
        // System.out.println(temp.toString());
        return temp.toString();
    }

    public abstract NetFSERecord generate(String line, int sensor) throws Exception;

    public String get(int field) {
        String temp = "";
        int len = 0;
        switch (field) {
        case (NetFSE.FIELD_START_TS):
            temp = Long.toHexString(this.getTimestamp().getTime() / 1000);
            len = 8;
            break;
        case (NetFSE.FIELD_DST_IP):
            temp = Long.toHexString(NetFSEUtil.convertIPtoLong(this.dstAddr));
            len = 8;
            break;
        case (NetFSE.FIELD_SRC_IP):
            temp = Long.toHexString(NetFSEUtil.convertIPtoLong(this.getSrcAddr()));
            len = 8;
            break;
        case (NetFSE.FIELD_DST_PORT):
            temp = Integer.toHexString(this.dstPort);
            len = 4;
            break;
        default:
            temp = null;
            break;
        }
        if (temp != null) {
            while (temp.length() < len)
                temp = "0" + temp;
        }
        return temp;
    }

    public String getCSVColNames() {
        return "sensor,start_timestamp,stop_timestamp,src_ip,src_ip_quad,src_port,src_bytes,src_packets,dst_ip,dst_ip_quad,dst_port,dst_bytes,dst_packets,protocol";
    }

    public FlexRecord getFlexRecord() {
        FlexRecord temp = new FlexRecord();
        temp.values = new String[11];
        int idx = -1;
        temp.values[++idx] = this.getTimestamp().toString();
        if (this.stopTS != null)
            temp.values[++idx] = this.stopTS.toString();
        else
            temp.values[++idx] = "";
        temp.values[++idx] = this.getSrcAddr();
        temp.values[++idx] = this.srcPort + "";
        temp.values[++idx] = this.srcPkts + "";
        temp.values[++idx] = this.srcBytes + "";
        temp.values[++idx] = this.dstAddr;
        temp.values[++idx] = this.dstPort + "";
        temp.values[++idx] = this.dstPkts + "";
        temp.values[++idx] = this.dstBytes + "";
        temp.values[++idx] = this.proto + "";
        return temp;
    }

    public FlexRecordField[] getFlexRecordFields() {
        FlexRecordField[] temp = new FlexRecordField[11];
        int idx = -1;
        temp[++idx] = new FlexRecordField("Start Time", "startts", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_TIMESTAMP);
        temp[++idx] = new FlexRecordField("Stop Time", "endts", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_TIMESTAMP);
        temp[++idx] = new FlexRecordField("Src IP", "srcip", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_IP_ADDR);
        temp[++idx] = new FlexRecordField("Src Port", "srcport", FlexRecordField.TYPE_INT,
                FlexRecordField.SUB_TYPE_PORT);
        temp[++idx] = new FlexRecordField("Src Pkts", "srcpkts", FlexRecordField.TYPE_LONG,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("Src Bytes", "srcbytes", FlexRecordField.TYPE_LONG,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("Dst IP", "dstip", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_IP_ADDR);
        temp[++idx] = new FlexRecordField("Dst Port", "dstport", FlexRecordField.TYPE_INT,
                FlexRecordField.SUB_TYPE_PORT);
        temp[++idx] = new FlexRecordField("Dst Pkts", "dstpkts", FlexRecordField.TYPE_LONG,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("Dst Bytes", "dstbytes", FlexRecordField.TYPE_LONG,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("Protocol", "proto", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_NONE);
        return temp;
    }

    public int[] getIndexedFields() {
        int[] temp = { NetFSE.FIELD_START_TS, NetFSE.FIELD_DST_IP, NetFSE.FIELD_SRC_IP, NetFSE.FIELD_DST_PORT };
        return temp;
    }

    /***************************************************************************
     * Return the millisecond portion of this record's start timestamp
     * 
     * @return The milliseconds for this record's start time
     */
    public int getStartMillis() {
        String timeStr = "" + getTimestamp();
        return Integer.parseInt(timeStr.substring(timeStr.length() - 4));
    }

    public Timestamp getStartTS() {
        return this.getTimestamp();
    }

    /***************************************************************************
     * Return the millisecond portion of this record's stop timestamp
     * 
     * @return The milliseconds for this record's end time
     */
    public int getStopMillis() {
        String timeStr = "" + stopTS;
        return Integer.parseInt(timeStr.substring(timeStr.length() - 4));
    }

    public Timestamp getEndTS() {
        return this.stopTS;
    }

    public void setDstIP(long dstIP) {
        this.dstAddr = NetFSEUtil.convertLongToIP(dstIP);
        this.dstIP = dstIP;
    }

    public void setDstPort(int dstPort) {
        this.dstPort = dstPort;
    }

    public long getDstIP() {
        return dstIP;
    }

    public int getProtocol() {
        return this.proto;
    }

    public int getDstPort() {
        return dstPort;
    }

    public void setEndTS(Timestamp stopTS) {
        this.stopTS = stopTS;
    }

    public long getDstBytes() {
        return this.dstBytes;
    }

    public long getSrcBytes() {
        return this.srcBytes;
    }
    
    public int getSrcPort() {
        return this.srcPort;
    }

    public long getDstPackets() {
        return this.dstPkts;
    }

    public long getSrcPackets() {
        return this.srcPkts;
    }
    
    public String toXML() {
        StringBuffer temp = new StringBuffer();
        temp.append("<" + this.getTypeName() + " sensorid=\"" + sensor + "\"");
        temp.append(" startts=\"" + this.getStartTS() + "\"");
        temp.append(" endts=\"" + this.getEndTS() + "\"");
        temp.append(" srcip=\"" + this.getSrcAddr() + "\"");
        temp.append(" dstip=\"" + this.getDstAddr() + "\"");
        temp.append(" srcport=\"" + this.getSrcPort() + "\"");
        temp.append(" dstport=\"" + this.getDstPort() + "\"");
        temp.append(" srcbytes=\"" + this.getSrcBytes() + "\"");
        temp.append(" dstbytes=\"" + this.getDstBytes() + "\"");
        temp.append(" srcpkts=\"" + this.getSrcPackets() + "\"");
        temp.append(" dstpkts=\"" + this.getDstPackets() + "\"");
        temp.append(" protocol=\"" + this.getProtocol() + "\""); 
        temp.append("/>");
        return temp.toString();
    }

}